' Bin paster bas.
' Pastes bins into a big bin, with optional padding
' and generates a .h file with an index using offsets

' fbc binpaster.bas cmdlineparser.bas mtparser.bas

#include "cmdlineparser.bi"
#include "mtparser.bi"

Dim Shared As uByte mainBin (16383)
Dim Shared As Integer mainBinIndex

Sub usage
	Print "Usage:"
	Print
	Print "$ binpaster [pad_to=XXXX] index=index.h out=out.bin files=file1,file2,..."
End Sub

Sub writeToBin (d As uByte)
	mainBin (mainBinIndex) = d
	If mainBinIndex < 16383 Then mainBinIndex = mainBinIndex + 1
End Sub

Function makeConstant (a As String) As String
	Dim i As Integer
	Dim As String outps, m

	outps = ""
	For i = 1 To Len (a)
		m = Mid (a, i, 1)
		If Not ((m >= "A" And m <="Z") OR (m >= "a" And m <= "z") Or (m >= "0" And m <= "9")) Then
			outps = outps & "_"
		Else
			outps = outps & Ucase (m)
		End If
	Next

	Return outps
End Function

Dim As String files (255)
Dim As Integer padTo
Dim As Integer i, j, fIn, fOut
Dim As String mandatory (2) = { "index", "out", "files" }
Dim As uByte d

Print "MK1 1.0 binpaster v0.1 20180405 ~ ";

sclpParseAttrs
If Not sclpCheck (mandatory ()) Then usage: End

parseTokenizeString sclpGetValue ("files"), files (), ",", "#"

fOut = FreeFile
Open sclpGetValue ("index") For Output As #fOut

Print #fOut, "// Index file to " & sclpGetValue ("out")
Print #fOut, "// Generated by binpaster.exe v0.1 20180405"
Print #fOut, "// Copyleft 2018 by The Mojon Twins"
Print #fOut, ""

Print "Reading & Indexing ~ ";

i = 0: While files (i) <> ""
	Print #fOut, "#define " & makeConstant (files (i)) & "_OFFS " & mainBinIndex

	fIn = FreeFile
	Open files (i) For Binary As #fIn
	While Not Eof (fIn)
		Get #fIn, , d
		writeToBin d
	Wend
	Close #fIn

	i = i + 1
Wend
Print #fOut, ""
Close #fOut 

padTo = Val (sclpGetValue ("pad_to"))
If padTo Then 
	Print "Padding to " & padTo & " ";

	If padTo >= mainBinIndex Then 
		Print "~ ";
		mainBinIndex = padTo
	Else 
		Print "~ Current bin size = " & mainBinIndex & ", will NOT pad! ~ ";
	End If
End If

Print "Writing ~ ";

Kill sclpGetValue ("out")
fOut = FreeFile
Open sclpGetValue ("out") For Binary As #fOut

For i = 0 To mainBinIndex - 1
	Put #fOut, , mainBin (i)
Next i 

Close #fOut

Print "DONE!"



